package com.example.lenovo_.myactivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lenovo_.healthyangel.*;
import com.example.lenovo_.myentity.UserEntity;
import com.example.lenovo_.myutils.SendUtils;
import com.example.lenovo_.myutils.SharedPfUtils;
import com.example.lenovo_.myutils.UrlUtils;
import com.example.lenovo_.myutils.UserUtils;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.Builder;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 登录Activity
 */
public class LoginActivity extends MyActivity implements OnClickListener {

    private ProgressDialog dialog;

    private EditText etUserName;
    private EditText etUserPsw;

    private Button btnLogin;

    private TextView tvReg, tvForget;

    private SharedPfUtils mSharedManager;

    Ihander h1 = new Ihander();// 接收线程发送的信息

    UserEntity user;

    SendUtils send = new SendUtils();// 发送和接收的信息
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //调用父类的onCreate方法
        super.onCreate(savedInstanceState);
        //初始化顶部控件
        //initTopBar(0, "用户登录", 0);

        initView();
        //调用此声明变量的getIsKeepUser方法，检查其是否保留登录信息，如果保留了：
        if (mSharedManager.getIsKeepUser()) {

            // 初始化全局用户
            //UserUtils中声明UserEntity型的user对象，其所使用的UserEntity类中的五个方法
            UserUtils.user.setUserId(mSharedManager.getId() + "");
            UserUtils.user.setUserName(mSharedManager.getName());
            UserUtils.user.setUserPsw(mSharedManager.getPassword());
            UserUtils.user.setUserImgUrl(mSharedManager.getUserImgUrl());

            System.out.println("缓存的全局用户Id为：" + UserUtils.user.getUserId());
            //打开活动MainActivity并结束当前的LoginActivity
            Intent in = new Intent(this, MainActivity.class);
            startActivity(in);
            LoginActivity.this.finish();
        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    //返回LoginActivity对应的int型值
    protected int getLayoutActivity() {
        return R.layout.layout_activity_login;
    }

    private void initView() {

        etUserName = (EditText) findViewById(R.id.et_username);
        etUserPsw = (EditText) findViewById(R.id.et_userpassword);

        btnLogin = (Button) findViewById(R.id.btn_login);

        tvReg = (TextView) findViewById(R.id.tv_reg);
        tvForget = (TextView) findViewById(R.id.tv_forget);

        btnLogin.setOnClickListener(this);
        tvReg.setOnClickListener(this);
        tvForget.setOnClickListener(this);

        mSharedManager = new SharedPfUtils(LoginActivity.this, SharedPfUtils.SPFILEUSERINFO);
        //send对象的setRequestPath方法设置请求路径为用户登录的接口http://123.207.190.85/healthyangel/public/user/sign_in
        send.setRequestPath(UrlUtils.UrlUserLogin);
    }

    // 对填写的用户信息是否为空进行判断
    private boolean isUserInOk() {

        boolean flag = true;

        String strUserName = etUserName.getText().toString().trim();
        String strUserPsw = etUserPsw.getText().toString().trim();

        if (!strUserName.equals("") && !strUserPsw.equals("")) {
            user = new UserEntity(strUserName, strUserPsw);
        } else {
            Toast.makeText(this, "请填写完整", Toast.LENGTH_LONG).show();
            flag = false;
        }

        return flag;

    }

    // 跳转到注册页面
    private void toRegister() {
        toOtherActivity(RegisterActivity.class);
    }

    // 发送注册请求
    private void toLogin() {

        if (isUserInOk()) {
            dialogShow();
            StartRequest();

        }
    }

    //设置进度条对话
    private void dialogShow() {

        if (dialog == null) {
            dialog = new ProgressDialog(this);
        }

        dialog.setTitle("请等待");
        dialog.setMessage("正在登录中...");
        dialog.setCancelable(false);
        dialog.show();

    }

    public void show(int i) {

        if (dialog != null) {
            dialog.dismiss();
        }

        switch (i) {

            case 1:
                Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();
                // 跳转
                Intent in = new Intent(this, MainActivity.class);
                startActivity(in);
                LoginActivity.this.finish();
                break;

            case 2:
                Toast.makeText(this, "不存在该用户", Toast.LENGTH_LONG).show();
                break;

            case 3:
                Toast.makeText(this, "密码错误", Toast.LENGTH_LONG).show();
                break;

            case 4:
                Toast.makeText(this, "服务器出现故障", Toast.LENGTH_LONG).show();
                break;

            case 5:
                Toast.makeText(this, "请求超时", Toast.LENGTH_LONG).show();
                break;

            default:
                break;
        }

    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Login Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    // 新建子类Ihander用于处理线程发回的信息
    public class Ihander extends Handler {

        @Override
        public void handleMessage(Message msg) {
            //.what用来区分消息要做的事
            int flag = msg.what;

            switch (flag) {

                case 1:
                    show(1);
                    break;

                case 2:
                    show(2);
                    break;

                case 3:
                    show(3);
                    break;

                case 4:
                    show(4);
                    break;

                case 5:
                    show(5);
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.btn_login:
                toLogin();
                break;

            case R.id.tv_reg:
                toRegister();
                break;

            case R.id.tv_forget:
                //toOtherActivity(TestActivity.class);
                break;

            default:
                break;
        }

    }

    // Ihander h = new Ihander();
    private void StartRequest() {
        // 新建线程
        new Thread() {
            public void run() {

                try {
                    SendRequest();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    //获取数据库的数据
    /**
     * POST请求获取数据
     */
    private void SendRequest(){
        HttpURLConnection httpURLConnection = null;
        URL ServerUrl = null;
        int code;

        try {
            ServerUrl = new URL(send.getRequestPath());
            // 准备传输的数据
            //新声明一个JSON格式的对象，并将用户名、密码、flag、1作为请求内容
            send.setSendRequest(new JSONObject());
            send.getSendRequest().put("username", user.getUserName());
            send.getSendRequest().put("password", user.getUserPsw());
            System.out.println(send.getSendRequest().toString());

            httpURLConnection = (HttpURLConnection) ServerUrl.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            //设置超时
            System.setProperty("sun.NET.client.defaultConnectTimeout", "2000");
            System.setProperty("sun.net.client.defaultReadTimeout", "2000");
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定传送的内容类型是json对象，(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            // 连接，从上述url.openConnection()至此的配置必须要在connect之前完成，
            httpURLConnection.connect();

            // 现在通过输出流对象构建对象输出流对象，以实现输出可序列化的对象。
            DataOutputStream objOutputStrm = new DataOutputStream(httpURLConnection.getOutputStream());
            // 向对象输出流写出数据，这些数据将存到内存缓冲区中
            objOutputStrm.writeBytes(send.getSendRequest().toString());

            // flush输出流的缓冲
            objOutputStrm.flush();
            objOutputStrm.close();
            code = httpURLConnection.getResponseCode();

            //开始获取数据
            // 调用HttpURLConnection连接对象的getInputStream()函数,
            if(code == 200){
                InputStream intStrm = httpURLConnection.getInputStream();

                // 得到接收到的Json对象，并将原inputstream流转化成json对象
                BufferedReader streamReader = new BufferedReader(new InputStreamReader(intStrm, "UTF-8"));
                StringBuilder responseStrBuilder = new StringBuilder();

                String inputStr;
                while ((inputStr = streamReader.readLine()) != null)
                    responseStrBuilder.append(inputStr);
                System.out.println(responseStrBuilder.toString());

                JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());
                send.setReceResponce(jsonObject);
                System.out.println(jsonObject.toString());

                // 获取返回的数据
                JSONObject jsonObjectdata = send.getReceResponce().getJSONObject("data");
                System.out.println("登录时返回的用户信息为：" + jsonObjectdata);
                int flag = jsonObjectdata.getInt("flag");

                // 登录成功则进入App 同时保存信息 初始化用户
                if (flag == 1) {
                    String tempUserName = jsonObjectdata.getString("name");
                    String tempUserPsw = jsonObjectdata.getString("password");
                    int tempUserId = jsonObjectdata.getInt("id");
                    String tempUserUrl = jsonObjectdata.getString("head_path");

                    mSharedManager.setIsKeepUser(true);
                    mSharedManager.setName(tempUserName);
                    mSharedManager.setPassword(tempUserPsw);
                    mSharedManager.setId(tempUserId);
                    mSharedManager.setUserImgUrl(tempUserUrl);

                    // 初始化全局用户
                    UserUtils.user.setUserId(tempUserId + "");
                    UserUtils.user.setUserName(tempUserName);
                    UserUtils.user.setUserPsw(tempUserPsw);
                    UserUtils.user.setUserImgUrl(tempUserUrl);

                    System.out.println("用户名为：" + UserUtils.user.getUserName());

                    h1.sendEmptyMessage(1);// 成功

                } else if (flag == 2) {
                    h1.sendEmptyMessage(2);// 不存在
                } else if (flag == 3) {
                    h1.sendEmptyMessage(3);// 密码错误
                }
            }
            else{
                h1.sendEmptyMessage(4);// 服务器出现故障（返回超时，已经连上但是返回超时）比如apache没开或者端口没开mysql没开，不会抛出异常
            }
        } catch (Exception e) {
            e.printStackTrace();
            h1.sendEmptyMessage(5);//请求超时
        }
    }

}